package com.hm.shopping.auto.su.helper;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hm.base.vo.LoginSubscriberVo;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.util.EncryptUtil.AES;
import com.hm.core.SdkConfig;
import com.hm.shopping.auto.su.R;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 上午10:55:09 2017年6月5日
 * @version 1.0
 * @describe 获取当前登录用户相关信息
 */
@Slf4j
public class HmSessionFactory {

	public static String currentUserIdString() {
		Long currentUserId = currentUserId();
		if (null != currentUserId) {
			return currentUserId + "";
		}
		return null;
	}

	public static Long currentUserId() {
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			Object obj = request.getSession().getAttribute(R.Session.SUBSCRIBER_SESSION);
			if (null != obj) {
				LoginSubscriberVo subscriberVo = (LoginSubscriberVo) obj;
				return Long.parseLong(traceToken(subscriberVo.getToken())[0]);
			}

			String token = request.getHeader(SdkConfig.REMOTE_CLIENT_AUTHORIZATION);
			if (null != token) {
				return Long.parseLong(traceToken(token)[0]);
			}
			return null;
		} catch (Exception e) {
			log.error("token解析失败", e);
			throw ServiceException.warning(ErrorCode.NO_DATA_ACCESS);
		}
	}

	private static String[] traceToken(String token) {
		try {
			return AES.decrypt(token).split(":");
		} catch (Exception e) {
			log.error("token解析失败", e);
			throw ServiceException.warning(ErrorCode.NO_DATA_ACCESS);
		}
	}
}
